<template>
  <div class="search-component">
    <el-button class="search-toggle" @click="toggleSearch" :aria-label="isOpen ? '关闭搜索' : '打开搜索'" circle text>
      <el-icon>
        <Search />
      </el-icon>
    </el-button>

    <el-dialog v-model="isOpen" :append-to-body="true" :fullscreen="isMobile" custom-class="search-dialog"
      :show-close="false" :width="isMobile ? '100%' : '700px'" :top="isMobile ? '0' : '5vh'"
      :modal-class="isDarkMode ? 'search-modal-dark' : 'search-modal-light'" destroy-on-close align-center>
      <div class="search-header">
        <el-icon class="search-icon">
          <Search />
        </el-icon>
        <el-input v-model="searchQuery" placeholder="搜索文章、标签..." class="search-input" ref="searchInput"
          @input="performSearch" clearable />
        <el-button class="close-button" @click="closeSearch" circle text>
          <el-icon>
            <Close />
          </el-icon>
        </el-button>
      </div>

      <div class="search-content">
        <div v-if="searchQuery.length === 0" class="search-empty">
          <p>请输入关键词进行搜索</p>
          <div class="popular-keywords">
            <span>热门关键词：</span>
            <el-tag v-for="keyword in popularKeywords" :key="keyword" class="keyword-tag"
              @click="selectKeyword(keyword)" size="small" effect="plain" type="info">
              {{ keyword }}
            </el-tag>
          </div>
        </div>

        <div v-else-if="loading" class="search-loading">
          <el-icon class="loading-icon" :size="40">
            <Loading />
          </el-icon>
          <p>正在搜索...</p>
        </div>

        <div v-else-if="searchResults.length === 0" class="search-no-results">
          <p>未找到与"{{ searchQuery }}"相关的内容</p>
          <p class="search-suggestions">建议：</p>
          <el-card class="suggestion-card" shadow="never">
            <el-collapse>
              <el-collapse-item title="查看搜索建议" name="1">
                <ul>
                  <li>检查您的拼写</li>
                  <li>尝试使用更通用的关键词</li>
                  <li>尝试使用相关的同义词</li>
                </ul>
              </el-collapse-item>
            </el-collapse>
          </el-card>
        </div>

        <div v-else class="search-results">
          <div class="result-section" v-if="postResults.length > 0">
            <el-divider content-position="left">文章</el-divider>
            <el-scrollbar max-height="300px">
              <ul class="result-list">
                <li v-for="result in postResults" :key="result.id" class="result-item">
                  <router-link :to="`/posts/${result.id}`" class="result-link" @click="closeSearch">
                    <h4 class="result-item-title" v-html="highlightMatch(result.title)"></h4>
                    <p class="result-item-excerpt" v-html="highlightMatch(result.summary)"></p>
                    <div class="result-item-meta">
                      <span class="result-item-date">{{ result.date }}</span>
                      <div class="result-item-tags">
                        <el-tag v-for="tag in result.tags" :key="tag" class="result-item-tag" size="small"
                          effect="plain">
                          {{ tag }}
                        </el-tag>
                      </div>
                    </div>
                  </router-link>
                </li>
              </ul>
            </el-scrollbar>
          </div>
          <div class="result-section" v-if="tagResults.length > 0">
            <el-divider content-position="left">标签</el-divider>
            <div class="result-tags">
              <router-link v-for="tag in tagResults" :key="tag.id" :to="`/posts?tagId=${tag.id}`" class="result-tag"
                @click="closeSearch">
                <el-tag type="info" effect="plain">
                  <span v-html="highlightMatch(tag.tagName)"></span>
                  <el-badge :value="tag.count" class="result-tag-count" />
                </el-tag>
              </router-link>
            </div>
          </div>
        </div>
      </div>

      <div class="search-footer">
        <div class="search-shortcuts">
          <span class="shortcut">
            <kbd>↑</kbd> <kbd>↓</kbd>
            <span class="shortcut-desc">导航</span>
          </span>
          <span class="shortcut">
            <kbd>Enter</kbd>
            <span class="shortcut-desc">选择</span>
          </span>
          <span class="shortcut">
            <kbd>Esc</kbd>
            <span class="shortcut-desc">关闭</span>
          </span>
        </div>

        <div class="advanced-search-link">
          <router-link to="/advanced-search" @click="closeSearch">
            <el-button text type="primary">
              <el-icon class="el-icon--left">
                <Plus />
              </el-icon>
              高级搜索 (ElasticSearch)
            </el-button>
          </router-link>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import {
  Search,
  Close,
  Loading,
  Plus
} from '@element-plus/icons-vue'
import { getResult } from '../api/search.js'
// 判断是否是移动设备
const isMobile = ref(window.innerWidth <= 768)
const isDarkMode = ref(document.documentElement.classList.contains('dark-theme'))

// 监听窗口大小变化
const handleResize = () => {
  isMobile.value = window.innerWidth <= 768
}

// 监听主题变化
const handleThemeChange = () => {
  isDarkMode.value = document.documentElement.classList.contains('dark-theme')
}

// 搜索状态
const isOpen = ref(false)
const searchQuery = ref('')
const loading = ref(false)
const searchInput = ref(null)

const allPosts = ref([])

// 提取所有标签
const allTags = ref([])

// 热门关键词
const popularKeywords = ref(['Vue3', 'Mysql', 'SpringBoot', 'Java', 'Linux', 'Python'])

// 搜索结果
const searchResults = ref([])
const postResults = computed(() => {
  return searchResults.value.filter(item => item.type === 'post')
})
const tagResults = computed(() => {
  // console.log(searchResults.value.filter(item => item.type === 'tag'));
  
  return searchResults.value.filter(item => item.type === 'tag')
})

// 执行搜索
const performSearch = () => {
  if (searchQuery.value.trim() === '') {
    searchResults.value = []
    return
  }

  loading.value = true

  // 模拟搜索延迟

  const query = searchQuery.value.toLowerCase().trim()
  const results = []

  // 搜索文章
  allPosts.value.forEach(post => {
    
    const titleMatch = post.title.toLowerCase().includes(query)
    const summaryMatch = post.summary.toLowerCase().includes(query)
    post.tagNames = post.tagNames || [];
    const tagMatch = post.tagNames.forEach(tag => tag.toLowerCase().includes(query))
    if (titleMatch || summaryMatch || tagMatch) {
      results.push({
        ...post,
        type: 'post',
        relevance: titleMatch ? 3 : (summaryMatch ? 2 : 1)
      })
    }
  })

  // 搜索标签
  allTags.value.forEach(tag => {
    if (tag.tagName.toLowerCase().includes(query)) {
      results.push({
        ...tag,
        type: 'tag',
        relevance: 2
      })
    }
  })

  // 按相关性排序
  results.sort((a, b) => b.relevance - a.relevance)

  searchResults.value = results
  loading.value = false
  // 模拟网络延迟
}

// 高亮匹配文本
const highlightMatch = (text) => {
  if (!text || !searchQuery.value.trim()) return text

  const regex = new RegExp(`(${searchQuery.value.trim()})`, 'gi')
  return text.replace(regex, '<mark>$1</mark>')
}

// 选择关键词
const selectKeyword = (keyword) => {
  searchQuery.value = keyword
  performSearch()
}

// 打开搜索
const toggleSearch = () => {
  isOpen.value = !isOpen.value
  if (isOpen.value) {
    // 自动聚焦搜索输入框
    nextTick(() => {
      searchInput.value?.input?.focus()
    })
  }
  // 初始化搜索结果
  getResult().then(res => {
    allPosts.value = res.data.postList
    allTags.value = res.data.tagsList
  })
}

// 关闭搜索
const closeSearch = () => {
  isOpen.value = false
  searchQuery.value = ''
  searchResults.value = []
}

// 键盘快捷键处理
const handleKeyDown = (e) => {
  // 如果按下Esc键，关闭搜索
  if (e.key === 'Escape') {
    closeSearch()
  }

  // 如果按下Ctrl+K或Cmd+K，打开搜索
  if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
    e.preventDefault()
    toggleSearch()
  }
}

// 挂载和卸载事件监听器
onMounted(() => {
  document.addEventListener('keydown', handleKeyDown)
  window.addEventListener('resize', handleResize)
  document.addEventListener('DOMContentLoaded', handleThemeChange)

  // 监听主题变更
  const observer = new MutationObserver(() => {
    handleThemeChange()
  })

  observer.observe(document.documentElement, {
    attributes: true,
    attributeFilter: ['class'],
  })
})

onBeforeUnmount(() => {
  document.removeEventListener('keydown', handleKeyDown)
  window.removeEventListener('resize', handleResize)
})

// 为父组件暴露方法
defineExpose({
  toggleSearch
})
</script>

<style scoped>
.search-component {
  position: relative;
}

.search-toggle {
  --el-button-text-color: var(--color-text);
  --el-button-hover-text-color: var(--color-primary);
  font-size: 20px;
}

.search-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.search-dialog :deep(.el-dialog__header) {
  display: none;
}

.search-modal-dark {
  background-color: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(4px);
}

.search-modal-light {
  background-color: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(4px);
}

.search-header {
  display: flex;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid var(--color-border);
  background-color: var(--color-card);
}

.search-icon {
  margin-right: 0.75rem;
  color: var(--color-text-light);
}

.search-input {
  flex: 1;
}

.search-input :deep(.el-input__wrapper) {
  background-color: transparent;
}

.close-button {
  margin-left: 0.5rem;
}

.search-content {
  padding: 1rem;
  overflow-y: auto;
  max-height: calc(100vh - 250px);
  background-color: var(--color-card);
}

.search-empty,
.search-loading,
.search-no-results {
  padding: 2rem 0;
  text-align: center;
  color: var(--color-text-light);
}

.popular-keywords {
  margin-top: 1rem;
}

.keyword-tag {
  margin: 0.25rem;
  cursor: pointer;
}

.keyword-tag:hover {
  color: var(--color-primary);
}

.loading-icon {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.search-suggestions {
  margin: 1rem 0 0.5rem;
  font-weight: 600;
}

.suggestion-card {
  max-width: 400px;
  margin: 0 auto;
  background-color: var(--color-card);
  border: 1px solid var(--color-border);
}

.suggestion-card :deep(.el-collapse) {
  border: none;
}

.suggestion-card :deep(.el-collapse-item__header) {
  background-color: transparent;
  border-bottom: none;
  justify-content: center;
  color: var(--color-primary);
}

.suggestion-card :deep(.el-collapse-item__content) {
  padding-bottom: 0;
}

.search-no-results ul {
  display: inline-block;
  text-align: left;
  margin: 0 auto;
}

.search-results {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.result-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.result-item {
  margin-bottom: 1rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid var(--color-border);
}

.result-item:last-child {
  border-bottom: none;
}

.result-link {
  display: block;
  color: var(--color-text);
  text-decoration: none;
}

.result-link:hover {
  color: var(--color-primary);
}

.result-item-title {
  font-size: 1.1rem;
  margin-bottom: 0.5rem;
}

.result-item-excerpt {
  font-size: 0.9rem;
  margin-bottom: 0.5rem;
  color: var(--color-text-light);
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}

.result-item-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.75rem;
}

.result-item-date {
  color: var(--color-text-light);
}

.result-item-tags {
  display: flex;
  gap: 0.5rem;
}

.result-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.75rem;
}

.result-tag {
  text-decoration: none;
}

.result-tag-count {
  margin-left: 5px;
}

.search-footer {
  padding: 0.75rem 1rem;
  background-color: var(--color-background);
  border-top: 1px solid var(--color-border);
  border-radius: 0 0 8px 8px;
}

.search-shortcuts {
  display: flex;
  justify-content: center;
  gap: 1.5rem;
}

.shortcut {
  display: flex;
  align-items: center;
  font-size: 0.75rem;
  color: var(--color-text-light);
}

kbd {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background-color: var(--color-code-bg);
  border: 1px solid var(--color-border);
  border-radius: 3px;
  box-shadow: 0 1px 1px var(--color-shadow);
  font-family: var(--font-mono);
  font-size: 0.7rem;
  line-height: 1;
  padding: 0.2rem 0.4rem;
  margin: 0 0.2rem;
}

.shortcut-desc {
  margin-left: 0.5rem;
}

.advanced-search-link {
  margin-top: 0.75rem;
  text-align: center;
  border-top: 1px solid var(--color-border);
  padding-top: 0.75rem;
}

mark {
  background-color: var(--color-mark-bg);
  color: inherit;
  padding: 0 0.1rem;
  border-radius: 2px;
}

@media (max-width: 768px) {
  .search-content {
    max-height: calc(100vh - 180px);
  }

  .search-shortcuts {
    flex-wrap: wrap;
    gap: 1rem;
  }

  .advanced-search-link {
    margin-top: 0.5rem;
    padding-top: 0.5rem;
  }
}
</style>
